﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SQLServerHealthCheck.Model;
using AG.Utilities;


namespace SQLServerHealthCheck.SQLServer.IssueTypes
{
    public class ServiceCheckMaintenancePlanWithAutoShrink : IssueTypeCheckBase
    {

        public ServiceCheckMaintenancePlanWithAutoShrink()
        {
            IssueTypeId = 2011;
        }

        public override void Check()
        {
            try
            {
                
                HealthCheckDataContext dc = new HealthCheckDataContext(System.Configuration.ConfigurationManager.AppSettings["ConnectionStringSSHCDatabase"]);


                // Query for maintenance plans with auto shrink enabled

                var QryAutosShrink = from m in dc.MaintenanceSubPlans
                                     where m.HasAutoShrinkTask == true

                                     select m;


                IssueType issueType = dc.IssueTypes.FirstOrDefault(i => i.IssueTypeId == IssueTypeId);

                foreach (var maintenancePlan in QryAutosShrink.GroupBy(cust => cust.MaintenancePlan).Select(grp => grp.First()))
                {
                    
                    //Create new Issue

                    Issue issue = new Issue();
                    issue.IssueType = issueType;
                    issue.TargetId = maintenancePlan.ServiceId;
                    issue.Description = issueType.Description.Replace("{MaintenancePlan}", maintenancePlan.MaintenancePlan);

                    dc.Issues.InsertOnSubmit(issue);
                }

                dc.SubmitChanges();

            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }
        }

    }
}
